package io.yizoo.core.message;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.taobao.api.ApiException;
import io.yizoo.core.ConfigUtil;
import io.yizoo.core.LoginDingtalkService;
import io.yizoo.system.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
@Service("dingTalk")
public class DingtakMessageService extends AbstractMessageService {

    @Autowired
    private LoginDingtalkService loginDingtalkService;


    @Override
    public String sendMsg(MessageContext context) {

        super.validParam(context);
        Boolean isAll = context.getAll();
        if (isAll == null) {
            isAll = false;
        }
        String userIdListStr = "";
        if (!isAll) {
            context.setUserDelimiter(",");
            userIdListStr = getTargetUserIdListStr(context);
        }
        String tenant = context.getTenant();
        Map<String, Object> dingTalkConfig = ConfigUtil.getConfig(tenant);
        if (dingTalkConfig == null) {
            throw new RuntimeException("企业配置不存在，请联系管理员");
        }
        String agentId = (String)dingTalkConfig.get("agent_id");
        String accessToken = loginDingtalkService.getAccessToken(tenant);
        String corpid = (String) dingTalkConfig.get("corp_id");

        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2");
        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setAgentId(Long.parseLong(agentId));
        request.setUseridList(userIdListStr);
        request.setToAllUser(isAll);

        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        try {
            String encode = URLEncoder.encode("http://www.snbg365.com/v/system/login?loginType=dingtalk&key="+tenant, "utf-8");
            String urlStr = "dingtalk://dingtalkclient/action/openapp?corpid={}&container_type=work_platform&app_id={}&redirect_type=jump&redirect_url={}";
            String url = StringUtil.formatStr(urlStr, corpid, "0_"+agentId, encode);
            msg.setActionCard(new OapiMessageCorpconversationAsyncsendV2Request.ActionCard());
            msg.getActionCard().setTitle(context.getTitle());
            msg.getActionCard().setMarkdown(context.getContent());
            msg.getActionCard().setSingleTitle("查看详情");
            msg.getActionCard().setSingleUrl(url);
            msg.setMsgtype("action_card");
            request.setMsg(msg);
            OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(request, accessToken);
            System.out.println(rsp.getBody());
            if (rsp.getErrcode() != 0) {
                System.out.println("异步发送失败"+rsp.getErrmsg());
                throw new RuntimeException(rsp.getErrmsg());
            }
            return "success";
        } catch (UnsupportedEncodingException e) {
            System.out.println("编码错误"+e.getMessage());
            throw new RuntimeException(e);
        } catch (ApiException e) {
            System.out.println("异步发送失败"+e.getMessage());
            throw new RuntimeException(e);
        }
    }
}
